<?php
/**
 * User: day
 * Date: 2018/08/07
 * Time: 23:42
 */

namespace App\Services\ThirdAPI;


use common\utils\RedisKeys;
use App\Models\Order;
use App\Models\Game;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use common\enum\CommonEnum;
use common\utils\SysCode;

class FGAPIService {
    protected $apiName  = 'FG';
    const GameType = ["fish", "poker", "slot", "fruit"];

    /**
     * 代理商获取玩家游戏下注数据或总社获取玩家游戏下注日志   OK
     * @param int $startTime 抓取时间段的开始时间
     * @param int $endTime 抓取时间段的结束时间
     * @return string|unknown
     */
    public function getFGOrders($startTime, $endTime) {
        Log::info("FG 获取注单：" . date("Y-m-d H:i:s", $startTime) . " - " . date("Y-m-d H:i:s", $endTime));

        $url = config('app.rpcserver') . "/api/getOrders";
        $retValue = [];
        $redis = Redis::connection();
        foreach( self::GameType as $type ) {
            $redisKey = RedisKeys::FG_UPDATE_KEY . $type;
            $pageKey = $redis->get($redisKey);
            Log::info(sprintf("FG 请求接口 url: %s, type: %s, pageKey: %s", $url, $type, $pageKey));
            $res = GameApiService::request($url, 'get', [
                'api_name' => 'FG',
                'start_time' => $startTime,
                'end_time' => $endTime,
                'type' => $type,
                'page_key' => $pageKey
            ]);
            $retValue = array_merge($retValue, $res["data"]);
            if (isset($res['page_key']) && $res["page_key"] != "none") {
                // 更新 pageKey
                $redis->set($redisKey, $res["page_key"]);
            }
        }
        return $retValue;
    }

    /**
     * 获取fg游戏名字列表
     * @return array|bool
     */
    public function getFGGameNames()
    {
        $data = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $needUpdate = Redis::set(RedisKeys::FG_LOCK_GAMES, date("Y-m-d H:i:s"), 'nx', 'ex', 3600);
        if (!$data || $needUpdate) {
            $data = $this->getFGGameList();
        }
        $games = [];
        foreach ($data as $game) {
            $games[$game['extend']] = $game['name'];
        }
        return $games;
    }

    /**
     * 获取游戏列表
     */
    public function getFGGameList() {
        //fg将所有游戏归类到h5
        $url = config('app.rpcserver') . "/api/getGameList";
        $res = GameApiService::request($url, 'get', ['api_name' => $this->apiName]);
        $currentData = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $formatData = [];
        foreach ($currentData as $value) {
            $formatData[$value['game_code']] = $value;
        }
        $insertData = [];
        $partnerInfo = GameApiService::getApiPartnerInfoByName($this->apiName);

        if(!isset($res['data']) || !is_array($res['data'])){
            error_exit(SysCode::API_ERROR);
            Log::error("FG 获取游戏列表返回错误：" . json_encode($res));
        }

        foreach ($res['data'] as $value) {
            if (empty($formatData[$value['gamecode']])) {
                $insertData[] = array(
                    'partner_id' => $partnerInfo['id'],
                    'partner_name' => $partnerInfo['name'],
                    'name' => $value['name'],
                    'extend' => $value['service_id'],
                    'img_url' => $value['img'],
                    'game_code' => $value['gamecode'],
                    'game_url' => $value['game_url'],
                    'type' => $value['gt'],
                    'game_type' => CommonEnum::GAME_EGAME, // 电子游戏
                );
            }
        }
        if (count($insertData) > 0) {
            GameApiService::saveGame($insertData);
            if (!$res) {
                Redis::del(RedisKeys::FG_LOCK_GAMES);
                BaseHandler::error("FG FGAPIService::getFGGameList 保存游戏列表报错失败：" . json_encode($res->getErrors(), JSON_UNESCAPED_UNICODE));
                return error_exit(SysCode::INTERNAL_SERVER_ERROR, "FG FGAPIService::getFGGameList 保存游戏列表报错失败");
            }
        }
        $currentData = array_merge($currentData, $insertData);
        return $currentData;
    }
}